/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.utilities;

import java.io.BufferedReader;
import java.io.FileReader;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.*;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "sendEmail")
@ApplicationScoped
public class SendEmail {

    //@Resource(name = "mail/smarttmtiduappmail")
    //private Session session;
    public SendEmail() {
    }

    /**
     *
     * @param key
     * @param fileName
     * @param titleMessage
     * @param toWho
     * @throws Exception
     */
    public void sendMessage(String key, String fileName, String titleMessage, String toWho) throws Exception {
        //InitialContext ctx = new InitialContext();
        //Session session
        //      = (Session) ctx.lookup("mail/smarttmtiduappmail");
        // Or by injection.  
        //@Resource(name = "mail/<name>")  
        //private Session session;  

        // Create email and headers.  
        Message msg = new MimeMessage(getSession());
        msg.setSubject(titleMessage);
        msg.setRecipient(RecipientType.TO,
                new InternetAddress(
                        toWho,
                        toWho));

        
        msg.setFrom(new InternetAddress(
                FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.senderMail"),
                FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.subject")));

        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
                .getExternalContext().getContext();
        //System.out.println(ctx.getRealPath("/")+"WEB-INF/includes/emailTemplates/"+fileName+".html");
        //para weblogic
        // BufferedReader br = new BufferedReader(new FileReader(ctx.getRealPath("/") + "/WEB-INF/includes/emailTemplates/" + fileName + ".html"));
        BufferedReader br = new BufferedReader(new FileReader(ctx.getRealPath("/") + "WEB-INF/includes/emailTemplates/" + fileName + ".html"));
        StringBuilder sb;
        try {
            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
            String everything = sb.toString();
        } finally {
            br.close();
        }
        String aux = sb.toString();
        aux = aux.replace("XzUyM", key);
        msg.setContent(aux, "text/html; charset=utf-8");

        // Send email.  
        Transport.send(msg);
    }

    public Session getSession() {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.auth"));

        properties.setProperty("mail.smtp.host",FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.host") );
        properties.setProperty("mail.smtp.port",FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.port") );

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator {

        private PasswordAuthentication authentication;

        public Authenticator() {
            String username = FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.user");
            String password = FacesUtils.getMessageFromBundle(PropertiesApp.FILES_MESSAGES.PROPERTIES, "bean.sendMail.password");
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }
}
